package com.asialjim.wechat.spring.message;

import com.asialjim.wechat.message.WeChatMessageHandler;
import com.asialjim.wechat.message.handler.DefaultWeChatMessageHandler;
import com.asialjim.wechat.message.WeChatMessageHandlerSelector;
import lombok.Data;
import lombok.var;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <h1><em>ASIAL JIM JAVA DOC</em></h1><hr/>
 * <h2>CLASS DESCRIPTION <i>[ NAME: WeChatMessageHandlerSelectorImpl ]</i></h2><strong>
 * <p> we-chat message handler selector
 * </strong><p><p><em>Copyright &copy; Asial Jim Co., LTD</em><hr/>
 *
 * @author Asial Jim &nbsp;&nbsp; <span>Email:<a href="mailto:asialjim@hotmail.com">asialjim@hotmail.com</a> &nbsp;&nbsp; <a href="asialjim@qq.com">asialjim@qq.com</a></span>
 * @version 1.0.0
 * @since 2021/3/11   &nbsp;&nbsp; JDK 8
 */
@Data
public class WeChatMessageHandlerSelectorImpl implements WeChatMessageHandlerSelector, ApplicationContextAware {
    private static final Logger log = LoggerFactory.getLogger(WeChatMessageHandlerSelectorImpl.class);

    private ApplicationContext applicationContext;
    private Map<String, WeChatMessageHandler> messageHandlerMap;

    @Override
    public WeChatMessageHandler select(String messageTypeName){
        WeChatMessageHandler handler = messageHandlerMap.get(messageTypeName);

        if (Objects.isNull(handler)){
            handler = messageHandlerMap.get("DEFAULT");
            if (Objects.isNull(handler)){
                handler = new DefaultWeChatMessageHandler(null);
                messageHandlerMap.put("DEFAULT",handler);
            }
        }

        return handler;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        messageHandlerMap = new HashMap<>(1 << 3);
        this.applicationContext = applicationContext;
        var beanNames = applicationContext.getBeanNamesForType(WeChatMessageHandler.class);
        for (String beanName : beanNames) {
            WeChatMessageHandler handler = this.applicationContext.getBean(beanName, WeChatMessageHandler.class);
            if (Objects.isNull(handler)) {continue;}
            try {
                String messageTypeName = handler.messageTypeName();
                messageHandlerMap.put(messageTypeName, handler);
            } catch (Throwable e){
                log.error("\r\n\tarrangement we chat message handler error:[{}]",e.getMessage());
            }
        }
    }
}